package com.qili.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.inject.internal.util.$FinalizableReference;
import com.qili.annotation.TokenCheck;
import com.qili.base.controller.BaseController;
import com.qili.base.entity.BasePathConfig;
import com.qili.base.service.BasePathConfigService;
import com.qili.controller.supervisor.SupervisorController;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.core.utils.FileUtils;
import com.qili.entity.FileDTO;
import com.qili.entity.base.BaseDict;
import com.qili.entity.jc.JcProject;
import com.qili.entity.jc.JcProjectMilepost;
import com.qili.entity.jc.JcProjectStage;
import com.qili.entity.jc.dto.JcPayRecordDTO;
import com.qili.entity.jc.dto.JcProjectDTO;
import com.qili.entity.jc.dto.JcProjectMilepostDTO;
import com.qili.entity.supervisor.*;
import com.qili.entity.supervisor.dto.*;
import com.qili.entity.supplier.dto.ProjectPlaceDTO;
import com.qili.entity.sys.dto.SysRoleUserDTO;
import com.qili.entity.zx.ZxProject;
import com.qili.entity.zx.ZxProjectMilepost;
import com.qili.entity.zx.ZxProjectStage;
import com.qili.redis.RedisService;
import com.qili.service.SysUserService;
import com.qili.service.base.SupervisorProjectMilepostService;
import com.qili.service.base.SupervisorProjectStageService;
import com.qili.service.supervisor.*;
import com.qili.service.supplier.ProjectPlaceService;
import com.qili.util.*;
import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hwpf.model.ListData;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static java.util.Objects.isNull;

/**
 * @author zengyuli
 * @date 2021/9/27
 * @description 监理app端接口
 */
@Controller
@Slf4j
@RequestMapping("/app/supervisor")
public class AppSupervisorController extends BaseController {
    @Autowired
    private SupervisorProjectService supervisorProjectService;
    @Autowired
    private SupervisorProjectStageService supervisorProjectStageService;
    @Autowired
    private SupervisorProjectMilepostService supervisorProjectMilepostService;
    @Autowired
    private ProjectUnitConstructionService projectUnitConstructionService;
    @Autowired
    private ProjectLeaderService projectLeaderService;
    @Autowired
    private SupervisorFileService supervisorFileService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ProjectContractService projectContractService;

    @Autowired
    ProjectBigEventService projectBigEventService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    SupervisorProjectFormsService supervisorProjectFormsService;

    @Autowired
    SupervisorProjectFormsDataService supervisorProjectFormsDataService;

    @Autowired
    SupervisorPayRecordService  supervisorPayRecordService;

    @Autowired
    ProjectPlaceService projectPlaceService;

    @Autowired
    SupervisorProjectPayService supervisorProjectPayService;


    @Autowired
    UploadUtil uploadUtil;

    @Value("${supervisor.downloadPath}")
    private String uploadPath;


    @Value("${supervisor.fileTempPath}")
    private String fileTempPath;


    @ApiOperation(value = "/showSupervisorList", httpMethod = "POST", notes = "APP展示项目")
    @PostMapping(value = "showSupervisorList")
    @ResponseBody
    @TokenCheck
    public JsonUtil showSupervisorList(@RequestBody SupervisorProjectDTO supervisorProjectDTO) {

        String userId = supervisorProjectDTO.getUserId();
        if (StringUtils.isBlank(userId)) {
            return JsonUtil.error("参数获取失败");
        }
        supervisorProjectDTO.setDestatus("000");
        supervisorProjectDTO.setUserId(userId);
        supervisorProjectDTO.setField(humpToUnderline(supervisorProjectDTO.getField()));
        //判断是否为管理员 公司高层 工程部经理

        SysRoleUserDTO sysRoleUserDTO = new SysRoleUserDTO();
        sysRoleUserDTO.setUserId(userId);
        List<SysRoleUserDTO> sysRoleUserDTOS = sysUserService.selectRoleUserByUser(sysRoleUserDTO);
        if (sysRoleUserDTOS != null) {
            if (sysRoleUserDTOS.size() > 0) {
                for (int i = 0; i < sysRoleUserDTOS.size(); i++) {
                    SysRoleUserDTO sysRoleUserDTO1 = sysRoleUserDTOS.get(i);
                    String roleName = sysRoleUserDTO1.getRoleName();
                    if ("admin".equals(roleName) || "gsgc".equals(roleName) || "gcbjl".equals(roleName) || "zkjsry".equals(roleName)) {
                        supervisorProjectDTO.setUserId(null);
                        break;
                    }
                }
            }

        }
//        Subject subject = SecurityUtils.getSubject();
//        if (subject.hasRole("admin") || subject.hasRole("gsgc") || subject.hasRole("gcbjl") || subject.hasRole("zkjsry")) {
//            supervisorProjectDTO.setUserId(null);
//        }
        List<SupervisorProjectDTO> supervisorProjectDTOList = supervisorProjectService.showSupervisorListApp(supervisorProjectDTO);
        return JsonUtil.sucessWithData("返回列表成功", supervisorProjectDTOList);

    }

    // 查看项目列表详情
    @ApiOperation(value = "/showSupervisorDetail", httpMethod = "GET", notes = "APP项目详情")
    @GetMapping(value = "showSupervisorDetail")
    @ResponseBody
    @TokenCheck
    public JsonUtil appSupervisorDetail(String spf_prjid) {
        SupervisorProjectDTO supervisorProjectDTO = new SupervisorProjectDTO();
        supervisorProjectDTO.setId(spf_prjid);
        SupervisorProjectDTO dto = supervisorProjectService.selectSupervisorDetailApp(supervisorProjectDTO);
        // 实施地点
        ProjectPlaceDTO pacedto = new ProjectPlaceDTO();
        pacedto.setSupProjectId(spf_prjid);
        pacedto.setType("001");
        List<ProjectPlaceDTO> listpalce = projectPlaceService.selectPlace(pacedto);
        dto.setProjectPlacedtos(listpalce);

        // 查询付款方式
        SupervisorProjectPayDTO payDTO = new SupervisorProjectPayDTO();
        payDTO.setSppPrjid(spf_prjid);
        List<SupervisorProjectPayDTO> listpay = supervisorProjectPayService.selectSupervisorProjectPay(payDTO);
        dto.setPayLists(listpay);

        // 查询分包表
        ProjectContractDTO projectContract = new ProjectContractDTO();
        projectContract.setProjectId(spf_prjid);
        List<ProjectContract> listfb = projectContractService.selectPackge(projectContract);
        dto.setFblist(listfb);
        // 承建单位
        ProjectUnitConstructionDTO projectUnitConstruction = new ProjectUnitConstructionDTO();
        projectUnitConstruction.setSupervisorProjectId(spf_prjid);
        List<ProjectUnitConstructionDTO> listcj = projectUnitConstructionService.selectProjectUnitList(projectUnitConstruction);
        dto.setCjlist(listcj);



        return JsonUtil.sucessWithData("项目详情列表返回成功", dto);
    }


    @ApiOperation(value = "/showUnSupervisorList", httpMethod = "POST", notes = "承建单位")
    @GetMapping(value = "showUnSupervisorList")
    @ResponseBody
    @TokenCheck
    public JsonUtil showUnSupervisorList(String projectId) {
        ProjectUnitConstructionDTO unitConstructiondto = new ProjectUnitConstructionDTO();
        unitConstructiondto.setSupervisorProjectId(projectId);
        List<ProjectUnitConstructionDTO> list = projectUnitConstructionService.selectProjectUnitList(unitConstructiondto);
        return JsonUtil.sucessWithData("承建单位列表返回成功", list);
    }

    @ApiOperation(value = "/showOwnerList", httpMethod = "POST", notes = "业主单位")
    @GetMapping(value = "showOwnerList")
    @ResponseBody
    @TokenCheck
    public JsonUtil showOwnerList(String id) {
        ProjectLeaderDTO leaderdto = new ProjectLeaderDTO();
        leaderdto.setSupervisorProjectId(id);
        List<ProjectLeaderDTO> listyz = projectLeaderService.selectProjectLeaderList(leaderdto);
        return JsonUtil.sucessWithData("业主单位列表返回成功", listyz);
    }

    //排序字段处理
    public static String humpToUnderline(String name) {
        StringBuilder result = new StringBuilder();
        if (name != null && name.length() > 0) {
            // 将第一个字符处理成大写
            result.append(name.substring(0, 1).toUpperCase());
            // 循环处理其余字符
            for (int i = 1; i < name.length(); i++) {
                String s = name.substring(i, i + 1);
                // 在大写字母前添加下划线
                if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
                    result.append("_");
                }
                // 其他字符直接转成大写
                result.append(s.toUpperCase());
            }
        }
        return result.toString();
    }


    //项目阶段
    @ApiOperation(value = "/selectSupervisorStage", httpMethod = "GET", notes = "APP项目阶段")
    @GetMapping(value = "selectSupervisorStage")
    @ResponseBody
    @TokenCheck
    public JsonUtil selectSupervisorStage(String spf_prjid) {
        SupervisorProjectStageDTO dto = new SupervisorProjectStageDTO();
        dto.setProjectId(spf_prjid);
        List<SupervisorProjectStageDTO> listStage = supervisorProjectStageService.selectProjectStage(dto);
        return JsonUtil.sucessWithData("项目阶段返回成功", listStage);
    }

    // 项目里程碑
    @ApiOperation(value = "/selectSupervisorMilepost", httpMethod = "GET", notes = "APP项目里程碑")
    @GetMapping(value = "selectSupervisorMilepost")
    @ResponseBody
    @TokenCheck
    public JsonUtil selectSupervisorMilepost(String id, String stage_id) {

        ProjectContractDTO projectContract = new ProjectContractDTO();
        projectContract.setProjectId(id);
        // 20210707 zhaoyongke  修改：到货验收和合同清单 页面的分包页签 需要根据 创建项目 选择的是否有到货验收来显示
        projectContract.setInspectionMerchandise("1");
        List<ProjectContract> listcjht_fb = projectContractService.getProjectPackageByRole(projectContract);
        Boolean  showdhys=true;
        if(listcjht_fb==null ||  listcjht_fb.size()==0){
            showdhys=false;
        }
        SupervisorProjectMilepostDTO su = new SupervisorProjectMilepostDTO();
        su.setProjectId(id);
        su.setSupervisorProjectStageId(stage_id);
        List<SupervisorProjectMilepostDTO> AlistMilePost = supervisorProjectMilepostService.selectProjectmilepost(su);
        if(showdhys==false){
            if (AlistMilePost != null && AlistMilePost.size() > 0) {
                for (int i = 0; i < AlistMilePost.size(); i++) {
                    SupervisorProjectMilepostDTO supervisorProjectMilepostDTO = AlistMilePost.get(i);
                    String milepostNo = supervisorProjectMilepostDTO.getMilepostNo();
                    if("012".equals(milepostNo) ){
                        AlistMilePost.remove(i);
                        break;
                    }

                }

            }
        }

        return JsonUtil.sucessWithData("项目里程碑返回成功", AlistMilePost);
    }

    /**
     * @Author:zhaoyongke
     * @Description: 招标文件
     * @Date:10:49 2021/10/08
     */
    @ApiOperation(value = "/appMapper", httpMethod = "POST", notes = "查询阶段里程中的文件")
    @PostMapping(value = "appMapper")
    @ResponseBody
    @TokenCheck
    public JsonUtil appMapper(@RequestBody SupervisorProjectDTO dto) {
        try {
            String id = dto.getId();
            String stageid = dto.getStageId();
            String spmid = dto.getSpmId();
            String typewj = dto.getType();
            // 查询类型  002 代表查询这个阶段下的所有文件
            String querytype = dto.getQuerytype();
            String userId = dto.getUserId();
            if (StringUtil.isBlank(id) || StringUtil.isBlank(stageid) || StringUtil.isBlank(userId)) {
                return JsonUtil.error("参数获取失败");
            }
            Map<String, Object> map = new HashMap<>();
            //查询项目
            SupervisorProject project = supervisorProjectService.selectByPrimaryKey(id);
            // 查询阶段
            SupervisorProjectStage stage = new SupervisorProjectStage();
            stage.setId(stageid);
            stage = supervisorProjectStageService.selectByPrimaryKey(stage);

            if ("002".equals(querytype)) {
                // 查看某个阶段下的所有里程
                ArrayList listre = new ArrayList();
                // 查询阶段下所有里程的文件
                SupervisorProjectMilepostDTO milepost = new SupervisorProjectMilepostDTO();
                milepost.setSupervisorProjectStageId(stageid);
                milepost.setProjectId(id);
                List<SupervisorProjectMilepostDTO> selectMilepost = supervisorProjectMilepostService.selectProjectmilepost(milepost);
                // 遍历所有的里程
                for (int i = 0; i < selectMilepost.size(); i++) {
                    ArrayList list = new ArrayList();
                    SupervisorProjectMilepostDTO supervisorProjectMilepost = selectMilepost.get(i);
                    queryFilesByMile(supervisorProjectMilepost, typewj, id, list, userId);
                    supervisorProjectMilepost.setChilds(list);
                    listre.add(supervisorProjectMilepost);
                }
                // 集合数据
                map.put("listdata", listre);

            } else {
                //查看单一里程
                ArrayList listre = new ArrayList();
                // 查询某一个里程文件
                SupervisorProjectMilepostDTO milepost = new SupervisorProjectMilepostDTO();
                milepost.setId(spmid);
                milepost.setProjectId(id);
                List<SupervisorProjectMilepostDTO> suProjectMilepostDTOS = supervisorProjectMilepostService.selectProjectmilepost(milepost);
                SupervisorProjectMilepostDTO suProjectMilepostDTO = suProjectMilepostDTOS.get(0);
                ArrayList list = new ArrayList();
                queryFilesByMile(suProjectMilepostDTO, typewj, id, list, userId);
                suProjectMilepostDTO.setChilds(list);
                listre.add(suProjectMilepostDTO);
                // 集合数据
                map.put("listdata", listre);
                map.put("lcdto", milepost);
            }
            SupervisorProjectDTO pdto = new SupervisorProjectDTO();
            BeanUtils.copyProperties(project, pdto);
            pdto.setSpmId(spmid);
            //基本信息
            map.put("pdto", pdto);
            map.put("stagedto", stage);
            return JsonUtil.sucessWithData("获取成功", map);
        } catch (BeansException e) {
            e.printStackTrace();
            return JsonUtil.error("获取失败");
        }
    }


    public void queryFilesByMile(SupervisorProjectMilepostDTO milepost, String typewj, String id, ArrayList list, String userId) {
        List<ProjectContract> listsqs_fb = getProjectContracts(id, "001", userId);
        String milepostNo = milepost.getMilepostNo();
        BaseDict AoBaseDict = DictUtil.getDictByCode(DictTypes.PROJECT_MILEPOST, milepostNo);
        String wjcode = AoBaseDict.getBadtLevel3();

        if (StringUtil.isNotBlank(typewj)) {
            //只是查询检测日志
            wjcode = typewj;
        }
        if (StringUtil.isNotBlank(wjcode)) {
            String[] split = wjcode.split(",");
            for (int i = 0; i < split.length; i++) {
                String type = split[i];
                List<SupervisorFile> listjlzb = null;
                FileDTO dto1 = new FileDTO();
                if ("036".equals(type) || "106".equals(type) || "037".equals(type) || "088".equals(type) || "109".equals(type)) {
                    //咨询付款申请 查询  需要过滤掉图片
                    Example e = new Example(SupervisorFile.class);
                    Example.Criteria c = e.createCriteria();
                    c.andEqualTo("projectId", id).andEqualTo("spmId", milepost.getId()).andEqualTo("type", type).andIsNull("parentId");
                    listjlzb = supervisorFileService.selectByExample(e);
                    // 查询子集
                    // 检查旁站
                    if ("036".equals(type) || "037".equals(type) || "106".equals(type)) {
                        for (int j = 0; j < listjlzb.size(); j++) {
                            SupervisorFile supervisorFile = listjlzb.get(j);
                            SupervisorFile filechied = new SupervisorFile();
                            filechied.setParentId(supervisorFile.getId());
                            List<SupervisorFile> select = supervisorFileService.select(filechied);
                            listjlzb.get(j).setListchilds(select);
                        }
                    }
                    // 监理付款申请
                    if ("088".equals(type) || "109".equals(type)) {
                        for (int j = 0; j < listjlzb.size(); j++) {
                            SupervisorFile supervisorFile = listjlzb.get(j);
                            Example ex = new Example(SupervisorFile.class);
                            Example.Criteria cr = ex.createCriteria();
                            cr.andNotEqualTo("type", "113");
                            cr.andEqualTo("parentId", supervisorFile.getId());
                            List<SupervisorFile> select = supervisorFileService.selectByExample(ex);
                            listjlzb.get(j).setListchilds(select);
                        }
                    }
                    dto1.setFileList(listjlzb);
                } else if ("123".equals(type)) {
                    // 回款到账情况
                    SupervisorProjectDTO jc = new SupervisorProjectDTO();
                    jc.setId(id);
                    List<SupervisorPayRecordDTO> payRecordDTOS = supervisorPayRecordService.selectHk(jc);
                    if(payRecordDTOS!=null  && payRecordDTOS.size()>0){
                        for (int j = 0; j <payRecordDTOS.size() ; j++) {
                            SupervisorPayRecordDTO  payRecordDTO = payRecordDTOS.get(j);
                            String arrivalDate = payRecordDTO.getArrivalDate();
                            // 到账时间
                            if(StringUtils.isNotBlank(arrivalDate)){
                                String[] split1 = arrivalDate.split(",");
                                payRecordDTO.setChild1(split1);
                            }
                            // 到账金额
                            String arrivalMoney = payRecordDTO.getArrivalMoney();
                            if(StringUtils.isNotBlank(arrivalMoney)){
                                String[] split1 = arrivalMoney.split(",");
                                payRecordDTO.setChild2(split1);
                            }
                        }

                    }
                    dto1.setFileList(payRecordDTOS);
                } else {
                    SupervisorFile supervisorFile = new SupervisorFile();
                    supervisorFile.setType(type);
                    supervisorFile.setProjectId(id);
                    supervisorFile.setSpmId(milepost.getId());
                    listjlzb = supervisorFileService.select(supervisorFile);
                    dto1.setFileList(listjlzb);
                }
                //
                BaseDict AoBaseDictwj = DictUtil.getDictByCode(DictTypes.WJ, type);
                dto1.setFileName(AoBaseDictwj.getBadtName());
                dto1.setLctype(AoBaseDictwj.getBadtLevel3());
                //  1 2  3
                dto1.setFb(AoBaseDictwj.getBadtLevel15());
                if ("064".equals(type)  ||  "038".equals(type)   ||  "039".equals(type)    ||  "042".equals(type)  ||  "043".equals(type)   ||  "044".equals(type)  ||  "045".equals(type)) {
                    //  货物清单 和 到货验收相关文件
                    List<ProjectContract> listcjht_qd = getProjectContracts(id, "002", userId);
                    // 分包集合 编号
                    dto1.setFbList(listcjht_qd);
                    if("064".equals(type)){
                        // 貨物清单文件 不显示
                        if(listcjht_qd!=null  &&  listcjht_qd.size()>0 ){
                            list.add(dto1);
                        }
                    }else{
                        list.add(dto1);
                    }

                } else {
                    // 分包集合 编号
                    dto1.setFbList(listsqs_fb);
                    list.add(dto1);
                }




            }
        }


    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description: 查询加电、开箱检验列表
     * @Date:13:49 2021/10/12
     */
    @ApiOperation(value = "/appMapperList", httpMethod = "POST", notes = "查询加电/开箱记录")
    @PostMapping(value = "appMapperList")
    @ResponseBody
    @TokenCheck
    public JsonUtil appMapperList(@RequestBody SupervisorProjectDTO dto) {
        try {
            String id = dto.getId();
            String stageid = dto.getStageId();
            String spmid = dto.getSpmId();
            String type = dto.getType();
            // 父级Id
            String fileId = dto.getFileId();
            if (StringUtil.isBlank(id) || StringUtil.isBlank(stageid) || StringUtil.isBlank(spmid) || StringUtil.isBlank(type)) {
                return JsonUtil.error("参数获取失败");
            }
            Map<String, Object> map = new HashMap<>();
            //查询项目
            SupervisorProject project = supervisorProjectService.selectByPrimaryKey(id);
            // 查询里程
            // SupervisorProjectMilepost milepost = supervisorProjectMilepostService.selectByPrimaryKey(spmid);
            // 查询阶段
            // SupervisorProjectStage stage = supervisorProjectStageService.selectByPrimaryKey(stageid);
            ArrayList list = new ArrayList();
            List<SupervisorFile> listjlzb = null;
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setType(type);
            supervisorFile.setProjectId(id);
            supervisorFile.setSpmId(spmid);
            supervisorFile.setParentId(fileId);
            listjlzb = supervisorFileService.select(supervisorFile);
            List<ProjectContract> listsqs_fb = getProjectContracts(id, "001", dto.getUserId());
            // 查询子集合
            for (int j = 0; j < listjlzb.size(); j++) {
                SupervisorFile file = listjlzb.get(j);
                SupervisorFile filechied = new SupervisorFile();
                filechied.setParentId(file.getId());
                List<SupervisorFile> select = supervisorFileService.select(filechied);
                listjlzb.get(j).setListchilds(select);
            }
            //
            BaseDict AoBaseDictwj = DictUtil.getDictByCode(DictTypes.WJ, type);
            FileDTO dto1 = new FileDTO();
            dto1.setFileName(AoBaseDictwj.getBadtName());
            dto1.setLctype(AoBaseDictwj.getBadtLevel3());
            dto1.setFileList(listjlzb);
            // 分包集合
            dto1.setFbList(listsqs_fb);
            // 该文件是否分包
            dto1.setFb(AoBaseDictwj.getBadtLevel15());
            list.add(dto1);
            SupervisorProjectDTO pdto = new SupervisorProjectDTO();
            BeanUtils.copyProperties(project, pdto);
            pdto.setSpmId(spmid);
            // 集合数据
            map.put("listdata", list);

            //基本信息
            map.put("pdto", pdto);
            //map.put("lcdto", milepost);
            //.put("stagedto", stage);
            return JsonUtil.sucessWithData("获取成功", map);
        } catch (BeansException e) {
            e.printStackTrace();
            return JsonUtil.error("获取失败");
        }
    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description: 判断是否有 相关模块
     * @Date:13:25 2021/10/13
     */
    @ApiOperation(value = "/getImageMode", httpMethod = "POST", notes = "判断是否有相关模块")
    @PostMapping(value = "getImageMode")
    @ResponseBody
    @TokenCheck
    public JsonUtil getImageMode(@RequestBody SupervisorProjectDTO dto) {
        try {
            HashMap map = new HashMap();
            String projectId = dto.getProjectId();
            if (StringUtil.isBlank(projectId)  || StringUtil.isBlank(dto.getUserId()) ) {
                return JsonUtil.error("获取參數失敗");
            }
            String isjc = "";
            // 是否有旁站记录
            String ispz = "";
            String isdhys = "";
            String ybys = "";

            SupervisorProjectMilepostDTO su = new SupervisorProjectMilepostDTO();
            su.setProjectId(projectId);
            su.setMilepostNoApp("image");
            List<SupervisorProjectMilepostDTO> listmilepost = supervisorProjectMilepostService.selectProjectmilepost(su);
            for (int i = 0; i < listmilepost.size(); i++) {
                SupervisorProjectMilepostDTO supervisorProjectMilepostDTO = listmilepost.get(i);
                String milepostNo = supervisorProjectMilepostDTO.getMilepostNo();
                // 是否有检查 需要判断两个 里程 011 017
                if ("011".equals(milepostNo) || "017".equals(milepostNo)) {
                    isjc = "1";
                }
                if ("011".equals(milepostNo)) {
                    ispz = "1";
                }
                if ("012".equals(milepostNo)) {
                    isdhys = "1";
                }
                if ("013".equals(milepostNo)) {
                    ybys = "1";
                }
            }

            // 旁站记录 011

            // 材料设备进场  到货验收     012

            // 隐蔽验收记录和 隐蔽验收图片 013
            // 到货验收 判断
            if("1".equals(isdhys)){
                List<ProjectContract>  listfb=getProjectContracts(projectId, "002", dto.getUserId());
                if(listfb==null  || listfb.size()==0){
                    isdhys="0";
                }
            }
            SupervisorProjectDTO dtodata = new SupervisorProjectDTO();
            dtodata.setIsjc(isjc);
            dtodata.setIspz(ispz);
            dtodata.setIsdhys(isdhys);
            dtodata.setYbys(ybys);
            map.put("pdto", dtodata);

            return JsonUtil.sucessWithData("获取成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("获取失败");
        }


    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description: app 拍照上传 相关功能
     * @Date:10:37 2021/10/11
     */
    @ApiOperation(value = "/getUploadImageWj", httpMethod = "POST", notes = "获取需要上传图片的文件")
    @PostMapping(value = "getUploadImageWj")
    @ResponseBody
    @TokenCheck
    public JsonUtil getUploadImageWj(@RequestBody SupervisorProjectDTO dto) {
        try {
            String id = dto.getId();
            String wjtype = dto.getType();
            String userId = dto.getUserId();
            if (StringUtil.isBlank(id) || StringUtil.isBlank(wjtype)) {
                return JsonUtil.error("参数获取失败");
            }
            Map<String, Object> map = new HashMap<>();
            ArrayList list = new ArrayList();
            //检查记录
            SupervisorProjectMilepostDTO su = new SupervisorProjectMilepostDTO();
            su.setProjectId(id);
            su.setMilepostNoApp(dto.getType());
            List<SupervisorProjectMilepostDTO> listmilepost = supervisorProjectMilepostService.selectProjectmilepost(su);
            for (int i = 0; i < listmilepost.size(); i++) {
                SupervisorProjectMilepostDTO milepost = listmilepost.get(i);
                String milepostNo = milepost.getMilepostNo();
                String type = "";
                List<SupervisorFile> listjlzb = null;
                switch (dto.getType()) {
                    case "jc001":
                        if ("011".equals(milepostNo)) {
                            type = "036";
                        } else if ("017".equals(milepostNo)) {
                            type = "106";
                        }
                        break;
                    case "pz001":
                        if ("011".equals(milepostNo)) {
                            type = "037";
                        }
                        break;
                    case "cl001":
                        if ("012".equals(milepostNo)) {
                            // 材料进场检验报告
                            type = "039";
                        }
                        break;
                    case "dh001":
                        if ("012".equals(milepostNo)) {
                            // 到货验收图片
                            type = "043";
                        }
                        break;
                    case "jl001":
                        // 隐蔽验收记录
                        if ("013".equals(milepostNo)) {
                            // 隐蔽验收记录
                            type = "046";
                        }
                        break;
                    case "tp001":
                        // 隐蔽验收图片
                        if ("013".equals(milepostNo)) {
                            // 隐蔽验收图片
                            type = "047";
                        }
                    default:
                }
                if ("036".equals(type) || "106".equals(type) || "037".equals(type) || "088".equals(type) || "109".equals(type)) {
                    //咨询付款申请 查询  需要过滤掉图片
                    // 088 109  监理付款申请
                    // 036 检查记录  037  旁站记录
                    // 106 检查记录

                    Example e = new Example(SupervisorFile.class);
                    Example.Criteria c = e.createCriteria();
                    c.andEqualTo("projectId", id).andEqualTo("spmId", milepost.getId()).andEqualTo("type", type).andIsNull("parentId");
                    listjlzb = supervisorFileService.selectByExample(e);

                    // 检查旁站
                    if ("036".equals(type) || "037".equals(type) || "106".equals(type)) {
                        for (int j = 0; j < listjlzb.size(); j++) {
                            SupervisorFile supervisorFile = listjlzb.get(j);
                            ArrayList listchid = new ArrayList();
                            SupervisorFile filechied = new SupervisorFile();
                            filechied.setParentId(supervisorFile.getId());
                            List<SupervisorFile> select = supervisorFileService.select(filechied);
                            listjlzb.get(j).setListchilds(select);
                        }
                    }
                    // 监理付款申请
                    if ("088".equals(dto.getType()) || "109".equals(dto.getType())) {
                        for (int j = 0; j < listjlzb.size(); j++) {
                            SupervisorFile supervisorFile = listjlzb.get(j);
                            Example ex = new Example(SupervisorFile.class);
                            Example.Criteria cr = ex.createCriteria();
                            cr.andNotEqualTo("type", "113");
                            cr.andEqualTo("parentId", supervisorFile.getId());
                            List<SupervisorFile> select = supervisorFileService.selectByExample(ex);
                            listjlzb.get(j).setListchilds(select);
                        }
                    }

                } else {
                    SupervisorFile supervisorFile = new SupervisorFile();
                    supervisorFile.setType(type);
                    supervisorFile.setProjectId(id);
                    supervisorFile.setSpmId(milepost.getId());
                    listjlzb = supervisorFileService.select(supervisorFile);
                }
                //
                BaseDict AoBaseDictwj = DictUtil.getDictByCode(DictTypes.WJ, type);
                FileDTO dto1 = new FileDTO();
                dto1.setJdlcName(AoBaseDictwj.getBadtLevel1());
                dto1.setFileName(AoBaseDictwj.getBadtName());
                dto1.setType(AoBaseDictwj.getBadtCode());
                dto1.setSpmId(milepost.getId());
                dto1.setStageId(milepost.getSupervisorProjectStageId());
                dto1.setFileList(listjlzb);
                dto1.setFb(AoBaseDictwj.getBadtLevel15());
                dto1.setMilepost(milepost);
                list.add(dto1);
            }
            map.put("listdata", list);
            // 分包数据
            List<ProjectContract> listsqs_fb =null;
            if("cl001".equals(dto.getType())  ||   "dh001".equals(dto.getType()) ){
                 listsqs_fb = getProjectContracts(id, "002", userId);
            }else{
                 listsqs_fb = getProjectContracts(id, "001", userId);
            }
            map.put("fbdata", listsqs_fb);

            return JsonUtil.sucessWithData("获取成功", map);
        } catch (BeansException e) {
            e.printStackTrace();
            return JsonUtil.error("获取失败");
        }


    }

    /**
     * @param filedata
     * @param dto
     * @param request
     * @Author:zhaoyongke
     * @Description: app 上传照片
     * @Date:14:54 2021/10/12
     */
    @RequestMapping(value = "/addFile", method = RequestMethod.POST)
    @ResponseBody
    @TokenCheck
    public JsonUtil File(@RequestParam(value = "file", required = false) MultipartFile filedata, SupervisorProjectDTO dto, HttpServletRequest request) {
        JsonUtil re = new JsonUtil();
        String projectid = dto.getId();// 项目id
        String type = request.getParameter("type");//文件类型
        String lockkey = "jlwjapp_" + projectid + "_" + type;
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey, uuId);
            // redis 锁 防止 编号重复
            JsonUtil jsonUtil = ((AppSupervisorController) AopContext.currentProxy()).addFile(filedata, dto, request);
            re.setFlag(jsonUtil.isFlag());
            re.setData(jsonUtil.getData());
            re.setMsg(jsonUtil.getMsg());
            re.setJosnObj(jsonUtil.getJosnObj());
            re.setStatus(jsonUtil.getStatus());
        } catch (Exception ex) {
            re.setFlag(false);
            re.setMsg("文件上传异常，" + ex.getMessage());
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            System.out.println(ex.getMessage());
        } finally {
            unlock(lockkey, uuId);
            return re;
        }
    }

    /**
     * @param
     * @Author:zhaoyongke
     * @Description: 表单文件添加
     * @Date:9:29 2020/11/30
     */
    @ApiOperation(value = "/addForm", httpMethod = "POST", notes = "表单添加")
    @PostMapping(value = "addForm")
    @ResponseBody
    @TokenCheck
    public JsonUtil addForm(@RequestBody SupervisorProjectDTO dto) throws Exception {
        try {
            String type = dto.getType();// 文件類型
            String spf_prjid = dto.getId();// 項目id
            String spf_staid = dto.getStageId();// 阶段id
            String spf_milid = dto.getSpmId();// 里程id
            String fbCode = dto.getFbCode();// 分包
            String pcId = dto.getFbId();// 分包Id
            String fileId = dto.getFileId();// 文件表id  个别form 添加是针对某个文档操作 需要知道具体是哪个文件 fileId
            String userId = dto.getUserId();
            String userId1 = CommonUtil.getUserId();
            System.out.println("===type==="+type);
            System.out.println("===spf_prjid==="+spf_prjid);
            System.out.println("===spf_staid==="+spf_staid);
            System.out.println("===fbCode==="+fbCode);
            System.out.println("===pcId==="+pcId);
            System.out.println("===userId==="+userId);
            /*承建单位不能上传监理文档*/
            if (StringUtil.isBlank(type) || StringUtil.isBlank(spf_prjid) || StringUtil.isBlank(spf_staid) || StringUtil.isBlank(fbCode) || StringUtil.isBlank(pcId) || StringUtil.isBlank(userId)) {
                return JsonUtil.error("参数获取失败");
            }
            String role = sysUserService.getUserRoleJlApp(spf_prjid, userId);
            if ("xmjl".equals(role) || "cj".equals(role) || "zjlgcs".equals(role) || "jlgcs".equals(role)) {
                if ("cj".equals(role)) {
                    BaseDict wjdict = DictUtil.getDictByCode(DictTypes.WJ, type);
                    String level11 = wjdict.getBadtLevel11();
                    if (level11.indexOf("cj") < 0) {
                        //  request.setAttribute("message", "您没有权限操作");
                        return JsonUtil.error("您没有权限操作");
                    }
                }
                if ("xmjl".equals(role)) {
                    if ("111".equals(type)) {
                        /*监理通知回执单*/
                        return JsonUtil.error("您没有权限操作");

                    }

                }

            } else {
                return JsonUtil.error("您没有权限操作");
            }
            if (StringUtil.isNotBlank(pcId)) {
                Boolean ischeck = checkFbCj(pcId, spf_prjid);
                if (!ischeck) {
                    return JsonUtil.error("该分包没有承建单位，不能上传文件");
                }
            }
            //查询项目详情
            SupervisorProjectDTO supervisorProjectdto = getSupervisorProjectDTO(spf_prjid);
            supervisorProjectdto.setFileId(fileId);
            // 获得文档流水号
            String orderCode = getFileOrderCode(spf_prjid, spf_staid, spf_milid, pcId, type);
            // 获取跳转路径
            // String re_url = getUrl(type, model);
            Map<String, Object> map = new HashMap<>();
            //特殊处理
            doSomeSpecialSthing(type, spf_prjid, fbCode, supervisorProjectdto, orderCode, userId, map);
            //解析文件数据
            try {
                parsingFileDataToList(type, fileId, spf_prjid, pcId, map);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 分包数据
            //基本信息
            map.put("pdto", supervisorProjectdto);
            map.put("id", supervisorProjectdto.getId());

            map.put("stageId", spf_staid);

            map.put("spmId", spf_milid);

            map.put("ind", Integer.valueOf(orderCode));

            map.put("spfFilecode", type);// 文件类型编号

            map.put("fbCode", fbCode);// 分包编号

            map.put("pcId", pcId);// 分包编号

            map.put("fileId", fileId); // 文件表id
            // 返回数据
            return JsonUtil.sucessWithData("获取成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("获取失败");
        }
    }

    /**
     * @param supervisorProjectFromsDTO
     * @Author:zhaoyongke
     * @Description: 表单保存文件
     * @Date:13:06 2020/11/30
     */
    @ApiOperation(value = "/addFormFile", httpMethod = "POST", notes = "表单添加")
    @PostMapping(value = "/addFormFile")
    @ResponseBody
    @TokenCheck
    public JsonUtil addFormFile(@RequestBody SupervisorProjectFromsDTO supervisorProjectFromsDTO) {
        JsonUtil re = new JsonUtil();
        JSONObject jsonObject = new JSONObject();
        try {
            // 项目Id
            String spfPrjid = supervisorProjectFromsDTO.getSpfPrjid();
            // 文档流水编号
            Integer fileInd = supervisorProjectFromsDTO.getFileInd();
            // 阶段Id
            String spfStaid = supervisorProjectFromsDTO.getSpfStaid();
            // 里程Id
            String spfMilid = supervisorProjectFromsDTO.getSpfMilid();
            // 文件类型
            String spfFilecode = supervisorProjectFromsDTO.getSpfFilecode();

            String fbCode = supervisorProjectFromsDTO.getFbCode();

            String pcId = supervisorProjectFromsDTO.getPcId();

            String wjNum = supervisorProjectFromsDTO.getWjNum();
            // 父级Id
            String parentId = supervisorProjectFromsDTO.getFileParentId();
            // -1-014
            String orderCode = supervisorProjectFromsDTO.getOrderCode();
            // 当前用户
            String userId = supervisorProjectFromsDTO.getUserId();
            if (StringUtil.isBlank(spfPrjid) || StringUtil.isBlank(spfStaid) || StringUtil.isBlank(spfMilid) || StringUtil.isBlank(pcId)) {
                return JsonUtil.error("参数获取失败");
            }
            //文件保存路径
            String AsFilePath = prepareFormSavePath(-1, supervisorProjectFromsDTO);

            //获取Form实例
            SupervisorProjectForms AoForms = getSupervisorProjectForms(supervisorProjectFromsDTO, AsFilePath);
            AoForms.setCreateDate(DateUtil.getCurrentDateString());
            supervisorProjectFormsService.insertSelective(AoForms);
            //            //针对个别表格数据  把表格数据保存到 form-data 表中 比如 加电检验记录表
            ArrayList<SupervisorProjectFormsData> AlstFormData = supervisorProjectFromsDTO.getFormDataList();
            if (!isNull(AlstFormData)) {
                addFormData(AlstFormData, AoForms.getSpfId());
            }
            String AsLinkId = AoForms.getSpfId();
            String parent = "";
            // 查询 路径
            String templateFilePath = "";
            if ("039".equals(spfFilecode)) {
                templateFilePath = FilePathUtil.getPathConfigTemplateFile("8801");
            } else if ("041".equals(spfFilecode)) {
                templateFilePath = FilePathUtil.getPathConfigTemplateFile("8802");
            } else if ("040".equals(spfFilecode)) {
                templateFilePath = FilePathUtil.getPathConfigTemplateFile("8803");
            }
            FileInputStream in = new FileInputStream(templateFilePath);//载入文档
            IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in,
                    TemplateEngineKind.Freemarker);
            IContext context = report.createContext();


            if ("039".equals(spfFilecode)) {
                // 材料进场检验报告
                context.put("projectName", supervisorProjectFromsDTO.getProjectName());
                // 监理单位
                context.put("jlName", supervisorProjectFromsDTO.getSpfF2());
                // 业主
                context.put("yzName", supervisorProjectFromsDTO.getSpfF3());
                // 承建单位
                context.put("cjName", supervisorProjectFromsDTO.getSpfF4());
                context.put("orderCode", supervisorProjectFromsDTO.getOrderCode());
                for (int i = 0; i < AlstFormData.size(); i++) {
                    SupervisorProjectFormsData formsData = AlstFormData.get(i);
                    if (formsData.getData10() == null) {
                        AlstFormData.get(i).setData10("");
                    }
                }

                context.put("data", AlstFormData);

            } else if ("041".equals(spfFilecode)) {
                // 加电检验记录表
                context.put("projectName", supervisorProjectFromsDTO.getProjectName());
                // 地点
                context.put("place", supervisorProjectFromsDTO.getSpfF2());
                // 设备名称
                context.put("sbname", supervisorProjectFromsDTO.getSpfF3());
                //日期
                context.put("riqidate", supervisorProjectFromsDTO.getSpfF4());
                // 序列号
                context.put("xlhnum", supervisorProjectFromsDTO.getSpfF5());

                // 系统加电 是否相符
                context.put("jdis", supervisorProjectFromsDTO.getSpfF6());
                // 异常频次
                context.put("jdnum", supervisorProjectFromsDTO.getSpfF7());

                // 系统自检 是否相符
                context.put("xtis", supervisorProjectFromsDTO.getSpfF8());
                // 异常频次
                context.put("xtnum", supervisorProjectFromsDTO.getSpfF9());
                //文档头编号
                context.put("ordercode", orderCode);

                context.put("data", AlstFormData);


            } else if ("040".equals(spfFilecode)) {
                // 开箱检验
                context.put("projectName", supervisorProjectFromsDTO.getProjectName());
                // 监理单位
                context.put("jlName", supervisorProjectFromsDTO.getSpfF2());
                // 业主
                context.put("yzName", supervisorProjectFromsDTO.getSpfF3());
                // 承建单位
                context.put("cjName", supervisorProjectFromsDTO.getSpfF4());
                //日期
                context.put("riqidate", supervisorProjectFromsDTO.getSpfF5());
                // 厂商
                context.put("csName", supervisorProjectFromsDTO.getSpfF6());
                // 设备名称
                context.put("sbname", supervisorProjectFromsDTO.getSpfF8());
                // 检验地点
                context.put("place", supervisorProjectFromsDTO.getSpfF7());

                // 外包装

                // 挤压变形
                context.put("w1", supervisorProjectFromsDTO.getSpfF9());
                // 破 损
                context.put("w2", supervisorProjectFromsDTO.getSpfF10());
                // 封口是否开封
                context.put("w3", supervisorProjectFromsDTO.getSpfF11());
                // 表面字迹
                context.put("w4", supervisorProjectFromsDTO.getSpfF12());

                // 破受潮湿
                context.put("w5", supervisorProjectFromsDTO.getSpfF13());
                // 腐蚀
                context.put("w6", supervisorProjectFromsDTO.getSpfF14());

                // 内部设备

                // 变  形
                context.put("n1", supervisorProjectFromsDTO.getSpfF15());
                // 磨  损
                context.put("n2", supervisorProjectFromsDTO.getSpfF16());
                // 表面漆层划伤
                context.put("n3", supervisorProjectFromsDTO.getSpfF17());
                // 设备固定螺丝是否有拆装的痕迹
                context.put("n4", supervisorProjectFromsDTO.getSpfF18());

                // 包装材料（泡沫垫层，包装袋等）
                context.put("n5", supervisorProjectFromsDTO.getSpfF19());

                // 资料 // 合格证
                context.put("z1", supervisorProjectFromsDTO.getSpfF20());
                // 保修卡
                context.put("z2", supervisorProjectFromsDTO.getSpfF21());
                // 使用手册
                context.put("z3", supervisorProjectFromsDTO.getSpfF22());
                // 其他
                context.put("z4", supervisorProjectFromsDTO.getSpfF23());


                // 数    量
                context.put("num", supervisorProjectFromsDTO.getSpfF24());
                context.put("xh", supervisorProjectFromsDTO.getSpfF25());
                context.put("xlh", supervisorProjectFromsDTO.getSpfF26());
                context.put("yzfs", supervisorProjectFromsDTO.getSpfF27());

                context.put("csdb", supervisorProjectFromsDTO.getSpfF28());
                context.put("ordercode", orderCode);

                // context.put("data", AlstFormData);


            }

            // 根据模板生成文件
            createFile(report, context, AsFilePath);
            // 生成文件
            saveFile(AsFilePath, spfFilecode, spfPrjid, spfStaid, spfMilid, pcId, parentId, AsLinkId, fileInd, userId);
            // 更新状态
            if (StringUtil.isNotBlank(wjNum) && wjNum != null) {
                if ("045".equals(spfFilecode) || "039".equals(spfFilecode) || "042".equals(spfFilecode)) {
                    /*到货验收-------到货验收报告  材料进场  序列号验证记录  */
                    updateLcStatusDh(spfPrjid, spfStaid, spfMilid, wjNum, fbCode);
                } else {
                    updateLcStatus(spfStaid, spfMilid, wjNum);
                }

            }
            re.setFlag(true);
            re.setMsg("操作成功");
            re.setData(jsonObject);
        } catch (Exception e) {
            re.setMsg("操作失败" + e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        return re;
    }


    /**
     * @param AsStageId
     * @param AsMilePostId
     * @param fs_status
     * @Author:zhaoyongke
     * @Description:到货验收状态处理
     * @Date:9:46 2021/2/6
     */
    public void updateLcStatusDh(String projectId, String AsStageId, String AsMilePostId, String fs_status, String fbcode) {
        // 查询分包
        ProjectContract contract = new ProjectContract();
        contract.setCode(fbcode);
        contract.setProjectId(projectId);
        List<ProjectContract> listcon = projectContractService.select(contract);
        if (listcon.size() > 0) {
            contract = listcon.get(0);
            // 查询分包表
            String stepNum = contract.getStepNum();
            // 数据库取出的完成状态
            String finishstatus = contract.getFinishStatus();
            String[] ayStatus = stepNum.split(",");
            String asPostStartIdx = fs_status.substring(0, 1);// 例如  10  20  截取  为  1 , 2
            String strsatus = ayStatus[Integer.valueOf(asPostStartIdx) - 1];
            // 该里程的状态为 进行中  或未开始 或 本文件类型为未开始的状态
            if (strsatus.substring(1, 2).equals("0") && ("0".equals(finishstatus) || "1".equals(finishstatus))) {// 判断当前文件类型的状态
                ayStatus[Integer.valueOf(asPostStartIdx) - 1] = fs_status;// 更新文件类型状态
                String str = Arrays.toString(ayStatus).replace("[", "").replace("]", "").replace(" ", "");
                contract.setStepNum(str);
            }
            if ("0".equals(finishstatus)) {
                contract.setFinishStatus("1");
                //进行中
            }
            /*更新分包*/
            projectContractService.updateByPrimaryKey(contract);
            /*更新里程状态*/
            SupervisorProjectMilepost supervisorProjectMilepost = supervisorProjectMilepostService.selectByPrimaryKey(AsMilePostId);
            if ("0".equals(supervisorProjectMilepost.getFinishStatus())) {
                supervisorProjectMilepost.setFinishStatus("1");//进行中
            }
            supervisorProjectMilepostService.updateByPrimaryKey(supervisorProjectMilepost);
            /*处理阶段状态*/
            SupervisorProjectStage stage = supervisorProjectStageService.selectByPrimaryKey(AsStageId);
            String finishStatusjd = stage.getFinishStatus();//
            if ("0".equals(finishStatusjd)) {
                stage.setFinishStatus("1");//进行中
                supervisorProjectStageService.updateByPrimaryKey(stage);
            }

        }


    }


    /**
     * @param AsStageId
     * @param AsMilePostId
     * @Author:zhaoyongke
     * @Description: 修改里程 阶段状态
     * @Date:21:24 2020/12/17
     */
    public void updateLcStatus(String AsStageId, String AsMilePostId, String fs_status) {
        SupervisorProjectMilepost supervisorProjectMilepost = supervisorProjectMilepostService.selectByPrimaryKey(AsMilePostId);
        String finishStatuslc = supervisorProjectMilepost.getFinishStatus();//
        String stepNum = supervisorProjectMilepost.getStepNum();
        String[] ayStatus = stepNum.split(",");
        String asPostStartIdx = fs_status.substring(0, 1);// 例如  10  20  截取  为  1 , 2
        String strsatus = ayStatus[Integer.valueOf(asPostStartIdx) - 1];
        // 该里程的状态为 进行中  或未开始 或 本文件类型为未开始的状态
        String fs = strsatus.substring(1, 2);
        if (fs.equals("0") && ("0".equals(finishStatuslc) || "1".equals(finishStatuslc) || "3".equals(finishStatuslc))) {// 判断当前文件类型的状态
            ayStatus[Integer.valueOf(asPostStartIdx) - 1] = fs_status;// 更新文件类型状态
            String str = Arrays.toString(ayStatus).replace("[", "").replace("]", "").replace(" ", "");
            supervisorProjectMilepost.setStepNum(str);
        }

        if ("0".equals(finishStatuslc)) {
            supervisorProjectMilepost.setFinishStatus("1");//进行中
        }
        /*更新里程状态*/
        supervisorProjectMilepostService.updateByPrimaryKey(supervisorProjectMilepost);
        /*处理阶段状态*/
        SupervisorProjectStage stage = supervisorProjectStageService.selectByPrimaryKey(AsStageId);
        String finishStatusjd = stage.getFinishStatus();//
        if ("0".equals(finishStatusjd)) {
            stage.setFinishStatus("1");//进行中
            supervisorProjectStageService.updateByPrimaryKey(stage);
        }

    }

    /**
     * @param report
     * @param context
     * @param target
     * @Author:zhaoyongke
     * @Description: 根据模板生成文件
     * @Date:10:07 2021/10/12
     */
    public void createFile(IXDocReport report, IContext context, String target) {
        try {
            //创建字段元数据
            FieldsMetadata fm = report.createFieldsMetadata();
            //Word模板中的表格数据对应的集合类型
            fm.load("data", SupervisorProjectFormsData.class, true);
            //输出到本地目录
            FileOutputStream out = new FileOutputStream(new File(target));
            report.process(context, out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XDocReportException e) {
            e.printStackTrace();
        }
    }

    public void saveFile(String pFilePath, String pFileType, String pPrjId, String pStageId, String pMilePostId, String pPkgId, String pParentId, String pLinkId, Integer fileInd, String userId) throws Exception {
        SupervisorFile countFile = new SupervisorFile();
        countFile.setProjectId(pPrjId);
        countFile.setUrl(pFilePath);
        int countfile = supervisorFileService.selectCount(countFile);
        if (countfile == 0) {
            SupervisorFile AoFile = new SupervisorFile();
            //带.的后缀名
            String AsSuffix = FilePathUtil.getFileSufiix(pFilePath);
            //获取文件名称
            String AsFileName = FilePathUtil.getFileName(pFilePath);
            // 文件名称
            AoFile.setFileName(AsFileName);
            // 文件后缀
            AoFile.setFileType(AsSuffix);
            // 文件类型
            AoFile.setType(pFileType);
            // url
            AoFile.setUrl(pFilePath);
            //項目id
            AoFile.setProjectId(pPrjId);
            //阶段id
            AoFile.setStageId(pStageId);
            //里程id
            AoFile.setSpmId(pMilePostId);
            //分包id
            AoFile.setPcId(pPkgId);
            //父级id
            AoFile.setParentId(pParentId);
            // form 表Id
            AoFile.setLinkId(pLinkId);
            AoFile.setCreateBy(userId);
            if (fileInd != null) {
                AoFile.setInd(fileInd);
            }
            if (!"112".equals(pFileType)) {
                projectBigEventService.saveProejctBigEventApp(pPrjId, pMilePostId, pStageId, userId);
            }
            supervisorFileService.insertSelective(AoFile);
        }
        //材料设备进场检验报告
        if (pFileType.equals("039") && countfile == 0) {
            //获取材料设备进场检验报告插入数据
            List<List<String>> AlistTableData = WordUtil.getWordTableDataApp(pFilePath, 1, 6);
            //获取合同比对报告文件地址
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setProjectId(pPrjId);
            supervisorFile.setPcId(pPkgId);
            supervisorFile.setType("044");
            int AiCnt = supervisorFileService.selectCount(supervisorFile);
            if (AiCnt == 1) {
                supervisorFile = supervisorFileService.selectOne(supervisorFile);
                String AsSaveContactPath = supervisorFile.getUrl();
                WordUtil.compareContract(AsSaveContactPath, AlistTableData);
            } else if (AiCnt == 0) {
                throw new Exception("非常抱歉，项目ID:" + pPrjId + "的项目未发现合同比对报告，无法进行合同比对。");
            } else if (AiCnt > 1) {
                throw new Exception("非常抱歉，项目ID:" + pPrjId + "的项目发现多个合同比对报告，仅支持一个合同进行比对，请删除对于的合同对比报告。");
            }
        }
    }


    /**
     * @Author:zhaoyongke
     * @Description: 针对表单存在表格得情况  插入 form-data
     * @Date:11:55 2020/12/5
     */
    public void addFormData(List<SupervisorProjectFormsData> plstFormData, String formid) {
        for (int i = 0; i < plstFormData.size(); i++) {
            SupervisorProjectFormsData formsData = plstFormData.get(i);
            formsData.setSpfId(formid);
            supervisorProjectFormsDataService.insertSelective(formsData);
        }
    }

    private SupervisorProjectForms getSupervisorProjectForms(SupervisorProjectFromsDTO supervisorProjectFromsDTO, String psFilePath) {
        SupervisorProjectForms form = new SupervisorProjectForms();
        BeanUtil.copyNotNullBean(supervisorProjectFromsDTO, form);
        form.setSaveFilePath(psFilePath);
        form.setSpfId(IdUtil.simpleUUID());
        return form;
    }

    /**
     * @param poSupervisorProjectFromsDTO
     * @Author:Zhangshuo
     * @Description:
     * @Date:10:29 2020/12/4
     */
    private String prepareFormSavePath(int piFileCount, SupervisorProjectFromsDTO poSupervisorProjectFromsDTO) {
        // 准备上传参数
        String AsPrjName = poSupervisorProjectFromsDTO.getProjectName();
        String AsFileType = poSupervisorProjectFromsDTO.getSpfFilecode();
        String AsFbCode = poSupervisorProjectFromsDTO.getFbCode();
        String AsFpId = poSupervisorProjectFromsDTO.getBfcId();
        SupervisorFile AoSupervisorFile = getSupervisorFile(poSupervisorProjectFromsDTO);
        AoSupervisorFile.setType(AsFileType);

        String AsFileStuffix = ".doc";
        UploadType uploadType = prepareUploadType(0, AsPrjName, AsFileType, AsFbCode, AsFpId, AsFileStuffix, piFileCount, AoSupervisorFile, "", "");
        poSupervisorProjectFromsDTO.setFileInd(uploadType.getInd());
        String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
        return AsFilePath;
    }


    /**
     * @param poSupervisorProjectFromsDTO
     * @Author:Zhangshuo
     * @Description:
     * @Date:9:31 2020/12/4
     */
    private SupervisorFile getSupervisorFile(SupervisorProjectFromsDTO poSupervisorProjectFromsDTO) {
        SupervisorFile file = new SupervisorFile();
        file.setProjectId(poSupervisorProjectFromsDTO.getSpfPrjid());
        file.setStageId(poSupervisorProjectFromsDTO.getSpfStaid());
        file.setSpmId(poSupervisorProjectFromsDTO.getSpfMilid());
        if (StringUtil.isNotBlank(poSupervisorProjectFromsDTO.getPcId())) {
            file.setPcId(poSupervisorProjectFromsDTO.getPcId());
        }
        return file;
    }

    private void parsingFileDataToList(String type, String fileId, String pPrjId, String pPkgId, Map<String, Object> mapdata) throws Exception {
        switch (type) {
            case "039"://材料检验
                //获取合同比对报告文件地址
                SupervisorFile supervisorFile = new SupervisorFile();
                supervisorFile.setProjectId(pPrjId);
                supervisorFile.setPcId(pPkgId);
                supervisorFile.setType("044");
                int AiCnt = supervisorFileService.selectCount(supervisorFile);
                if (AiCnt == 1) {
                    supervisorFile = supervisorFileService.selectOne(supervisorFile);
                    String AsSaveContactPath = supervisorFile.getUrl();
                    // 读取合同对比报告中的数据
                    List<List<String>> AlstWordData = null;
                    try {
                        AlstWordData = WordUtil.getWordTableData(AsSaveContactPath, 1, 6);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new Exception("文件解析异常，请按照模板文件");
                    }

                    // 已经全部进场的 不需要在显示  根据 合同对比报告中的 实际数量和清单数量的值 对比
                    List<List<String>> dataAdd = new ArrayList<>();
                    try {
                        if (AlstWordData != null) {
                            if (AlstWordData.size() > 0) {
                                for (int i = 0; i < AlstWordData.size(); i++) {
                                    List<String> strings = AlstWordData.get(i);
                                    int size = strings.size();
                                    if (strings != null) {
                                        if (strings.size() > 2) {
                                            // 清单数量
                                            String snum = strings.get(5) + "";
                                            // 进场数量
                                            String sjnum = strings.get(7) + "";
                                            if (StringUtil.isNumeric(snum) && StringUtil.isNumeric(sjnum)) {
                                                BigDecimal sDouble = new BigDecimal(snum);
                                                BigDecimal sjDouble = new BigDecimal(sjnum);
                                                if (sjDouble.compareTo(sDouble) > 0 || sjDouble.compareTo(sDouble) == 0) {

                                                } else {
                                                    dataAdd.add(strings);
                                                }
                                            } else {
                                                dataAdd.add(strings);
                                            }
                                        }

                                    }


                                }
                            }

                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    mapdata.put("htlist", dataAdd);
                    mapdata.put("htlistJson", JSONArray.toJSONString(dataAdd));
//                    model.addAttribute("htlist", dataAdd);
//                    model.addAttribute("htlistJson", JSONArray.toJSONString(dataAdd));
                } else if (AiCnt == 0) {
                    throw new Exception("非常抱歉，项目ID:" + pPrjId + "的项目未发现合同比对报告，无法进行合同比对。");
                } else if (AiCnt > 1) {
                    throw new Exception("非常抱歉，项目ID:" + pPrjId + "的项目发现多个合同比对报告，仅支持一个合同进行比对，请删除对于的合同对比报告。");
                }
                break;
            case "040"://开箱检验
            case "041"://加电检测
                // 查询文件
                SupervisorFile file = new SupervisorFile();
                file.setId(fileId);
                file = supervisorFileService.selectByPrimaryKey(file);
                String AsFilePath = file.getUrl();
                List<List<String>> AlstFileTableData = null;
                if (StringUtil.isNotBlank(AsFilePath)) {
                    //读取word中表格数据
                    try {
                        AlstFileTableData = WordUtil.getWordTableData(file.getUrl(), 1, 6);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new Exception("文件解析异常，请按照模板文件");
                    }
                }
                if (AlstFileTableData != null) {
                    if (AlstFileTableData.size() > 0) {
                        for (int j = 0; j < AlstFileTableData.size(); j++) {
                            String str = AlstFileTableData.get(j) + "";
                            if (StringUtil.isNotBlank(str)) {
                                if (str.indexOf("单位代表") > 0) {
                                    AlstFileTableData.remove(j);
                                }
                            }
                        }
                    }

                }

                mapdata.put("devlist", AlstFileTableData);

                // model.addAttribute("devlist", AlstFileTableData);
                break;
        }
    }

    /**
     * @param type
     * @param spf_prjid
     * @param fbCode
     * @param supervisorProjectdto
     * @param orderCode
     * @Description:特殊处理
     * @Author:Zhangshuo
     * @Date:11:19 2020-12-19
     */
    private void doSomeSpecialSthing(String type, String spf_prjid, String fbCode, SupervisorProjectDTO supervisorProjectdto, String orderCode, String userId, Map<String, Object> mapdata) {

        ProjectUnitConstructionDTO unitConstructiondto = new ProjectUnitConstructionDTO();
        unitConstructiondto.setSupervisorProjectId(spf_prjid);
        if ("039".equals(type) || "016".equals(type) || "036".equals(type) || "037".equals(type) || "040".equals(type) || "042".equals(type) || "045".equals(type)) {
            /*材料进场检验报告*/
            unitConstructiondto.setConstructionSubContractNumber(fbCode);
        }
        // 承建单位项目经理
        if (com.qili.core.shiro.Principal.hasRole("nupm")) {
            //承建单位
            unitConstructiondto.setProjectManager(userId);
        }
        if ("111".equals(type)) {
            /*监理通知回执单 需要查询监理通知选择的承建单位*/
            String fileId = supervisorProjectdto.getFileId();
            SupervisorFile fileparent = supervisorFileService.selectByPrimaryKey(fileId);
            String linkId = fileparent.getLinkId() + "";
            if (StringUtil.isNotBlank(linkId)) {
                SupervisorProjectForms form = supervisorProjectFormsService.selectByPrimaryKey(linkId);
                /*承建单位项目经理*/
                String cjManagerUserId = form.getSpfF30() + "";
                if (StringUtil.isNotBlank(cjManagerUserId)) {
                    unitConstructiondto.setProjectManager(cjManagerUserId);
                }
                String parentordercode = "JLTZ-" + form.getOrderCode();
                // model.addAttribute("parentordercode", parentordercode);
            }


        }
        List<ProjectUnitConstructionDTO> listcjlist = projectUnitConstructionService.selectProjectUnitList(unitConstructiondto);
        //承建单位名称
        ArrayList<String> AlstCjdwstr = new ArrayList<>();
        //承建合同名称
        ArrayList<String> AlstCjHtstr = new ArrayList<>();
        for (int i = 0; i < listcjlist.size(); i++) {
            AlstCjdwstr.add(listcjlist.get(i).getUnitConstruction());
            // 承建合同名称
            AlstCjHtstr.add(listcjlist.get(i).getConstructionContract());
        }
        String cj = AlstCjdwstr.toString();
        String cjstr = "";
        if (StringUtil.isNotBlank(cj)) {
            //截取前后【】
            cjstr = cj.replaceAll("\\[", "").replaceAll("\\]", "");
        }
        String cjht = AlstCjHtstr.toString();
        String cjhtstr = "";
        if (StringUtil.isNotBlank(cjht)) {
            //截取前后【】
            cjhtstr = cjht.replaceAll("\\[", "").replaceAll("\\]", "");
        }
        mapdata.put("cj", cjstr);
        mapdata.put("cjht", cjhtstr);
        if ("080".equals(type) || "060".equals(type) || "054".equals(type)) {
            // 监理 工作总结报告  查询统计文档列表
//            getFileTypeCountList(model, spf_prjid);
//            //获取项目分包及建设内容
//            getProjectUnitInfor(model, supervisorProjectdto, listcjlist);
        }
        if (type.equals("039")) {
            /*材料设备进场检验报告*/
            orderCode = "-" + fbCode + "-" + orderCode;
        } else if (type.equals("040") || type.equals("041")) {
            /*设备开箱检验报告 设备加电检测记录表*/
            //获取材料进场检验报告的序号
            String fileId = supervisorProjectdto.getFileId();
            SupervisorFile file = supervisorFileService.selectByPrimaryKey(fileId);
            String lnkid = file.getLinkId();
            SupervisorProjectForms from = supervisorProjectFormsService.selectByPrimaryKey(lnkid);
            orderCode = from.getOrderCode();
        }
        // 文件类型编号

        mapdata.put("orderCode", orderCode);
        mapdata.put("listcjlist", listcjlist);
        //到货验收报告
        if (listcjlist != null) {
            if (listcjlist.size() > 0) {
                ProjectUnitConstructionDTO unitConstructionDTO = listcjlist.get(0);
                //model.addAttribute("cjdto", unitConstructionDTO);
                mapdata.put("cjdto", unitConstructionDTO);
            }

        }

    }


    /**
     * @param type
     * @param model
     * @Author:zhaoyongke
     * @Description:根据type 获取路径
     * @Date:17:06 2020/12/1
     */
    public String getUrl(String type, Model model) {
        String re_url = "";
        switch (type) {

            case "036":
                re_url = "/supervisor/projectManager/ss-jcpz-jcjl-form";
                break;
            case "037":
                // 旁站记录
                re_url = "/supervisor/projectManager/ss-jcpz-pzjl-form";
                break;
            case "039":
                // 到货验收---材料设备进场检验报告
                re_url = "/supervisor/projectManager/dhys-cljcjy-form";
                break;
            case "040":
                // 设备开箱检验报告
                re_url = "/supervisor/projectManager/dhys-kxjy-form";
                break;
            case "041":
                // 设备加电检验报告
                re_url = "/supervisor/projectManager/dhys-jdjy-form";
                break;

            default:

        }
        return re_url;
    }


    /**
     * @param spf_prjid 项目ID
     * @param spf_milid 里程ID
     * @param fbid      分包ID
     * @param psType    文件类型
     * @Author:Zhangshuo
     * @Description:
     * @Date:12:25 2020/12/4
     */
    public String getFileOrderCode(String spf_prjid, String spf_staid, String spf_milid, String fbid, String psType) {
        SupervisorFile AoSupervisorFile = new SupervisorFile();
        AoSupervisorFile.setProjectId(spf_prjid);
        AoSupervisorFile.setStageId(spf_staid);
        AoSupervisorFile.setSpmId(spf_milid);
        AoSupervisorFile.setType(psType);
        if (StringUtil.isNotBlank(fbid)) {
            AoSupervisorFile.setPcId(fbid);
        }
        Integer count = 0;
        Map paraMap = new HashMap<>();
        paraMap.put("projectId", AoSupervisorFile.getProjectId());
        if ("055".equals(psType) || "061".equals(psType) || "081".equals(psType)) {
            // 特殊处理：初验： 055 验收报告 终验：061验收报告 验收阶段：081 验收报告 三种文档整体按顺序排列
            List<String> typeList = new ArrayList<String>();
            typeList.add("055");
            typeList.add("061");
            typeList.add("081");
            paraMap.put("typeList", typeList);
        } else if ("036".equals(psType) || "037".equals(psType)) {
            // 特殊处理：
            List<String> typeList = new ArrayList<String>();
            typeList.add("036");
            typeList.add("037");
            paraMap.put("type", AoSupervisorFile.getType());
        } else {
            if (StringUtils.isNotBlank(AoSupervisorFile.getPcId())) {
                paraMap.put("pcId", AoSupervisorFile.getPcId());
            }
            if (StringUtils.isNotBlank(AoSupervisorFile.getSpmId())) {
                paraMap.put("spmId", AoSupervisorFile.getSpmId());
            }
            paraMap.put("type", AoSupervisorFile.getType());
        }
        count = supervisorFileService.selectMaxOrderBySupervisorFile(paraMap) + 1;
        NumberFormat formatter = new DecimalFormat("000");
        String AsOrderNum = formatter.format(count);
        return AsOrderNum;
    }


    /**
     * @param spf_prjid
     * @Description:获取SupervisorProject
     * @Author:Zhangshuo
     * @Date:11:20 2020-12-19
     */
    private SupervisorProjectDTO getSupervisorProjectDTO(String spf_prjid) {
        SupervisorProjectDTO supervisorProjectdto = new SupervisorProjectDTO();
        //查询项目
        supervisorProjectdto.setId(spf_prjid);
        List<SupervisorProjectDTO> projectlist = supervisorProjectService.selectSupervisorProject(supervisorProjectdto);
        if (projectlist.size() > 0) {
            supervisorProjectdto = projectlist.get(0);
        }
        String names = "";
        String secondSupervisorEngineer = supervisorProjectdto.getSecondSupervisorEngineer();
        if (StringUtil.isNotBlank(secondSupervisorEngineer)) {
            String[] str = supervisorProjectdto.getSecondSupervisorEngineer().split(",");
            for (int x = 0; x < str.length; x++) {
                String name = sysUserService.selectByPrimaryKey(str[x]).getRealName();
                if (x == 0) {
                    names = name;
                } else {
                    names = names + "," + name;
                }
            }
            supervisorProjectdto.setSecondSupervisorEngineerName(names);
        }

        return supervisorProjectdto;
    }


    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public JsonUtil addFile(MultipartFile filedata, SupervisorProjectDTO dto, HttpServletRequest request) throws Exception {


//        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
//        def.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
        //返回数据
        JsonUtil re = new JsonUtil();
        String type = request.getParameter("type");//文件类型
        String projectid = dto.getId();// 项目id
        String lockkey = "jlwj_" + projectid + "_" + type;
        String uuId = IdUtil.simpleUUID();
        try {
//            lock(lockkey, uuId);
            String uploadtype = dto.getUploadType();
            String spmid = dto.getSpmId();// 里程id
            String stageId = dto.getStageId();//阶段id
            String fs_status = request.getParameter("fs_status");// 上传的时候 对应的状态p'r
            String fbId = request.getParameter("fbId");//分包表id
            JSONObject jsonObject = new JSONObject();
            String filename = filedata.getOriginalFilename();
            String userId = dto.getUserId();
            if (StringUtil.isNotBlank(fbId)) {
                Boolean ischeck = checkFbCj(fbId, projectid);
                if (!ischeck) {
                    re.setMsg("该分包没有承建单位，不能上传文件");
                    re.setFlag(false);
                    return re;
                }
            }
            String role = sysUserService.getUserRoleJlApp(projectid,userId);
            if ("xmjl".equals(role) || "cj".equals(role) || "zjlgcs".equals(role) || "jlgcs".equals(role)) {
                if ("cj".equals(role)) {
                    BaseDict wjdict = DictUtil.getDictByCode(DictTypes.WJ, type);
                    String level11 = wjdict.getBadtLevel11();
                    if (level11.indexOf("cj") < 0) {
                        re.setMsg("您没有权限上传文档");
                        re.setFlag(false);
                        return re;
                    }
                }

            } else {
                re.setMsg("您没有权限上传文档");
                re.setFlag(false);
                return re;
            }

            /*项目大事记*/
            projectBigEventService.saveProejctBigEventApp(projectid, spmid, stageId, userId);
            //对文件中图片和文件的名称做处理
            JsonUtil error = doSomeSpecialThings(dto, uploadtype);
            if (error != null) {
                re.setFlag(false);
                re.setMsg(error.getMsg());
                return error;
            }
            if ((StringUtil.isBlank(uploadtype)) || (!uploadtype.equals("002"))) {
                //更新阶段和里程状态
                updateStageAndMilePostStatus(spmid, stageId, fs_status, jsonObject, type, fbId);
            }
            //上传文件以及保存数据
            savedoUploadAndSaveFile(filedata, dto, uploadtype, userId, spmid, stageId, projectid, fbId, jsonObject, filename);

            if (jsonObject.get("wj_status") == null) {
                jsonObject.put("wj_status", "");
            }
            if (jsonObject.get("lc_status") == null) {
                jsonObject.put("lc_status", "");
            }
            if (jsonObject.get("jd_status") == null) {
                jsonObject.put("jd_status", "");
            }
            re.setData(jsonObject);
            re.setFlag(true);
            return re;
        } catch (Exception e) {
            e.printStackTrace();
            re.setFlag(false);
            re.setMsg("文件上传异常，" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return re;
    }


    /**
     * @param filedata
     * @param dto
     * @param uploadtype
     * @param userid
     * @param spmid
     * @param stageId
     * @param projectid
     * @param fbId
     * @param jsonObject
     * @param filename
     * @Description: 上传文件已经保存到数据库中
     * @Author:Zhangshuo
     * @Date:21:51 2020-12-20
     */
    @Transactional
    public void savedoUploadAndSaveFile(MultipartFile filedata, SupervisorProjectDTO dto, String uploadtype, String userid, String spmid, String stageId, String projectid, String fbId, JSONObject jsonObject, String filename) throws Exception {
        //上传文件
        String AsFileStuffix = FilePathUtil.getFileSufiix(filename);
        /*检验文件格式*/
        updatejyFileType(AsFileStuffix, dto.getType());
        /*校验文件名称*/
        updatejyFileName(filename, dto.getType());

        UploadType uploadType = getFileUploadType(dto, spmid, projectid, fbId, AsFileStuffix, uploadtype);
        LoadType loadType = uploadUtil.upload(filedata, uploadType);
        //文件名称
        String AsNewFileName = uploadType.getFileName();
        //保存文件表
        SupervisorFile filedto = saveSupervisorFile(dto, userid, spmid, stageId, projectid, fbId, loadType, AsNewFileName, uploadType.getInd());
        //解析文件数据
        jsonObject.put("id", filedto.getId());
        jsonObject.put("filename", AsNewFileName);
        HashMap map = new HashMap();
//        try {
//            map = saveparsingFileData(loadType.getFilePath(), dto, fbId);
//        } catch (Exception e) {
//            throw  new  Exception("请按照模板文件格式上传,目前只支持2007版以上的Word文件（后缀名为.docx）");
//        }
        /*reson 变更处理表更原因*/
        // jsonObject.put("bgreason", map.get("reason"));

    }

    /**
     * @param dto
     * @param userid
     * @param spmid
     * @param stageId
     * @param projectid
     * @param fbId
     * @param loadType
     * @param asNewFileName
     * @Author:Zhangshuo
     * @Description:保存数据到文件表
     * @Date:22:21 2020-12-08
     */
    public SupervisorFile saveSupervisorFile(SupervisorProjectDTO dto, String userid, String spmid, String stageId, String projectid, String fbId, LoadType loadType, String asNewFileName, Integer ind) throws Exception {
        SupervisorFile filedto = new SupervisorFile();
        filedto.setFileName(asNewFileName);
        filedto.setFileType(loadType.getSuffix());
        filedto.setType(dto.getType());
        filedto.setCreateBy(userid);
        filedto.setCreateDate(new Date());
        filedto.setUrl(loadType.getFilePath());
        filedto.setInd(ind);
        if (null != fbId && !"".equals(fbId)) {
            filedto.setPcId(fbId);// 分包id
        }
        filedto.setParentId(dto.getParentId());
        filedto.setPositionName(dto.getPositionName());
        filedto.setProjectId(projectid);// 项目id
        filedto.setSpmId(spmid);// 里程id
        filedto.setStageId(stageId);// 阶段id
        supervisorFileService.insert(filedto);
        supervisorFileService.setFilePathDics(filedto);
        // 解析文件  保存文本用于 智能检索
        try {
            supervisorFileService.parseFileToText(filedto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filedto;
    }


    /**
     * @param dto
     * @param spmid     里程ID
     * @param projectid 项目ID
     * @param fbId      分包ID
     * @Author:Zhangshuo
     * @Description:
     * @Date:12:34 2020/12/4
     */
    private UploadType getFileUploadType(SupervisorProjectDTO dto, String spmid, String projectid, String fbId, String psFileStuffix, String pUploadType) throws Exception {
        SupervisorProject AoSupervisorProject = supervisorProjectService.selectByPrimaryKey(projectid);
        String AsType = dto.getType();
        ProjectContract AoPackage = new ProjectContract();
        if (null != fbId && !"".equals(fbId)) {
            AoPackage = projectContractService.selectByPrimaryKey(fbId);
        }
        String AsFbCode = AoPackage.getCode();
        BaseDict AoBaseDict = DictUtil.getDictByCode(DictTypes.WJ, AsType + (StringUtil.isBlank(pUploadType) ? "" : pUploadType));
        String AsFpId = AoBaseDict.getBadtLevel2();

        if (StringUtil.isNotBlank(AsFpId)) {
            SupervisorFile AoSupervisorFile = new SupervisorFile();
            if (("040".equals(AsType) || "093".equals(AsType) || "036".equals(AsType) || "037".equals(AsType) || "106".equals(AsType) || "108".equals(AsType) || "109".equals(AsType) || "087".equals(AsType) || "088".equals(AsType)) && ("002".equals(pUploadType))) {
                /*附件通过parentId查询*/
                AoSupervisorFile.setParentId(dto.getParentId());
            } else {
                AoSupervisorFile.setProjectId(projectid);
                AoSupervisorFile.setSpmId(spmid);
                AoSupervisorFile.setPcId(fbId);
                AoSupervisorFile.setType(AsType);
            }
            UploadType uploadType = prepareFileUploadType(AoSupervisorProject, AsType, AsFbCode, AsFpId, psFileStuffix, dto.getFileCount(), AoSupervisorFile, pUploadType, dto.getPositionName());
            return uploadType;
        } else {
            throw new Exception("文件类型：" + AsType + "，未发现配置存储路径，请到数据字典中配置。");
        }
    }

    /**
     * @param
     * @Author:Zhangshuo
     * @Description:
     * @Date:10:51 2020/12/4
     */
    private UploadType prepareFileUploadType(SupervisorProject poSupervisorProject, String psFileType, String psFbCode, String psFpId, String psFileStuffix, int piFileCount, SupervisorFile poSupervisorFile, String pUploadType, String pPositionName) {
        return prepareUploadType(0, poSupervisorProject.getProjectName(), psFileType, psFbCode, psFpId, psFileStuffix, piFileCount, poSupervisorFile, pUploadType, pPositionName);
    }


    /**
     * @param type             上传类型 UploadType EnumByType
     * @param psPrjName        项目名称
     * @param psFileType       文件类型
     * @param psFbCode         分包编号
     * @param psFpId           路径配置表ID
     * @param poSupervisorFile
     * @Author:Zhangshuo
     * @Description:获取上传UploadType
     * @Date:10:03 2020/12/4
     */
    public UploadType prepareUploadType(int type, String psPrjName, String psFileType, String psFbCode, String psFpId, String psFileStuffix, int piFileCount, SupervisorFile poSupervisorFile, String pUploadType, String pPositionName) {
        // 获取文件名称
        String AsFileName = FileUtils.getFileName(psPrjName, psFileType, psFbCode, psFileStuffix, piFileCount, poSupervisorFile, pUploadType, pPositionName);
        // 替换项目名称
        ArrayList<String> placeHolder = new ArrayList<String>();
        placeHolder.add(psPrjName);
        placeHolder.add(psFbCode);
        placeHolder.add(pPositionName);
        UploadType uploadType = UploadType.getEnumByType(type);
        uploadType.setFileName(AsFileName);
        uploadType.setFilePathId(psFpId);
        uploadType.setPlaceholder(placeHolder);
        uploadType.setInd(poSupervisorFile.getInd());
        return uploadType;
    }

    /**
     * @param fileName
     * @param type
     * @Author:zhaoyongke
     * @Description: 校验文件名称
     * @Date:17:20 2021/1/12
     */
    public void updatejyFileName(String fileName, String type) throws Exception {
        BaseDict wjdict = DictUtil.getDictByCode(DictTypes.WJ, type);
        String isjy = wjdict.getBadtLevel7();
        String dictFileName = wjdict.getBadtName();
        if ("1".equals(isjy)) {
            if (fileName.indexOf(dictFileName) == -1) {
                throw new Exception("您上传的文件名称中必须包含：" + dictFileName);
            }
        }
    }

    /**
     * @param AsFileStuffix
     * @param type
     * @Author:zhaoyongke
     * @Description:校验文件类型 是否和字典中的值一致
     * @Date:16:51 2021/1/12
     */
    public void updatejyFileType(String AsFileStuffix, String type) throws Exception {
        BaseDict wjdict = DictUtil.getDictByCode(DictTypes.WJ, type);
        Boolean isTrue = false;
        /*文件类型是否正确判断*/
        String dicwjtype = wjdict.getBadtLevel6();
        if (StringUtil.isNotBlank(dicwjtype)) {
            String[] dictypesz = dicwjtype.split(",");
            if (dictypesz.length > 0) {
                for (int i = 0; i < dictypesz.length; i++) {
                    String wjtype = dictypesz[i].toLowerCase();
                    String stuffix = AsFileStuffix.toLowerCase() + "";
                    if (stuffix.indexOf(wjtype) != -1) {
                        isTrue = true;
                        break;
                    }
                }
            } else {
                isTrue = true;
            }
        } else {
            isTrue = true;
        }
        if (!isTrue) {
            throw new Exception("正确的文件格式为：" + dicwjtype);
        }
    }


    /**
     * @param spmid
     * @param stageId
     * @param fs_status
     * @param jsonObject
     * @Description:更新阶段和里程状态
     * @Author:Zhangshuo
     * @Date:22:31 2020-12-18
     */
    private void updateStageAndMilePostStatus(String spmid, String stageId, String fs_status, JSONObject jsonObject, String type, String fbId) {
        // 里程
        SupervisorProjectMilepost supervisorProjectMilepost = supervisorProjectMilepostService.selectByPrimaryKey(spmid);
        // 阶段
        SupervisorProjectStage stage = supervisorProjectStageService.selectByPrimaryKey(stageId);
        String stepNum = supervisorProjectMilepost.getStepNum();
        // 里程本身的状态
        String finishStatus = supervisorProjectMilepost.getFinishStatus();
        if ("038".equals(type) || "039".equals(type) || "042".equals(type) || "043".equals(type) || "044".equals(type) || "045".equals(type)) {
            //到货验收 里面的文件类型 单独处理 文件状态记录到分包表中了
            ProjectContract contract = projectContractService.selectByPrimaryKey(fbId);
            String stepNumFb = contract.getStepNum();
            String finishStatusFb = contract.getFinishStatus();// 里程本身的状态
            String[] ayStatus = stepNumFb.split(",");
            String asPostStartIdx = fs_status.substring(0, 1);// 例如  10  20  截取  为  1 , 2
            String strsatus = ayStatus[Integer.valueOf(asPostStartIdx) - 1];
            if (strsatus.substring(1, 2).equals("0") && ("0".equals(finishStatusFb) || "1".equals(finishStatusFb))) {// 判断当前文件类型的状态
                ayStatus[Integer.valueOf(asPostStartIdx) - 1] = fs_status;// 更新文件类型状态
                String str = Arrays.toString(ayStatus).replace("[", "").replace("]", "").replace(" ", "");
                contract.setStepNum(str);
                // 更新状态字符串
                if ("0".equals(finishStatusFb)) {
                    contract.setFinishStatus("1");//进行中
                }
                projectContractService.updateByPrimaryKey(contract);
                jsonObject.put("wj_status", "1");
            }
        } else {
            String[] ayStatus = stepNum.split(",");
            String asPostStartIdx = fs_status.substring(0, 1);// 例如  10  20  截取  为  1 , 2
            String strsatus = ayStatus[Integer.valueOf(asPostStartIdx) - 1];
            // 该里程的状态为 进行中  或未开始 或 本文件类型为未开始的状态
            if (strsatus.substring(1, 2).equals("0") && ("0".equals(finishStatus) || "1".equals(finishStatus) || "3".equals(finishStatus))) {// 判断当前文件类型的状态
                ayStatus[Integer.valueOf(asPostStartIdx) - 1] = fs_status;// 更新文件类型状态
                String str = Arrays.toString(ayStatus).replace("[", "").replace("]", "").replace(" ", "");
                supervisorProjectMilepost.setStepNum(str);
                // 更新状态字符串
                supervisorProjectMilepostService.updateByPrimaryKey(supervisorProjectMilepost);
                jsonObject.put("wj_status", "1");
            }
        }
        if ("0".equals(finishStatus)) {
            supervisorProjectMilepost.setFinishStatus("1");//进行中
            supervisorProjectMilepostService.updateByPrimaryKey(supervisorProjectMilepost);
            jsonObject.put("lc_status", "1");// 里程进行中
        }
        if ("0".equals(stage.getFinishStatus())) {
            stage.setFinishStatus("1");//进行中
            supervisorProjectStageService.updateByPrimaryKey(stage);
            jsonObject.put("jd_status", "1");// 阶段
        }
    }

    /**
     * @param dto
     * @param uploadtype
     * @Description:
     * @Author:Zhangshuo
     * @Date:21:48 2020-12-20
     */
    private JsonUtil doSomeSpecialThings(SupervisorProjectDTO dto, String uploadtype) {
        String AsType = dto.getType();
        //002 上传图片方式
        if ("002".equals(uploadtype) && !"093".equals(AsType) && !"040".equals(AsType)) {

            if ("108".equals(AsType) || "109".equals(AsType) || "087".equals(AsType) || "088".equals(AsType)) {
                //承建付款申请 和 监理付款申请 不包含部位
                String positonName = dto.getPositionName();
                dto.setPositionName("第" + positonName + "次");
            } else {
//                if (StringUtil.isBlank(dto.getPositionName())) {
//                    return JsonUtil.error("部位不允许为空！！");
//                } else {
//                    // 部位为汉字
//                    String reg = "[\\u4e00-\\u9fa5]+";
//                    boolean result = dto.getPositionName().matches(reg);
//                    if (!result) {
//                        return JsonUtil.error("部位请填写汉字！！");
//                    }
//                }
            }
        }
        return null;
    }


    /**
     * @param id
     * @Description:
     * @Author:Zhangshuo
     * @Date:15:06 2020-12-19
     */
    private List<ProjectContract> getProjectContracts(String id, String type, String userId) {
        ProjectContractDTO projectContract = new ProjectContractDTO();
        projectContract.setProjectId(id);
        String AsUserId = userId;
        //业主单位项目负责人和承建单位项目经理只查看自己负责的
        String userRole = sysUserService.getUserRoleJlApp(id, userId);
        if (StringUtils.isNotBlank(userRole)) {
            if ("yz".equals(userRole)) {
                projectContract.setProjectLeader(AsUserId);
            } else if ("cj".equals(userRole)) {
                projectContract.setProjectManager(AsUserId);
            }
        }
        // 20210707 zhaoyongke  修改：到货验收和合同清单 页面的分包页签 需要根据 创建项目 选择的是否有到货验收来显示
        if ("002".equals(type)) {
            projectContract.setInspectionMerchandise("1");
        } else {
            projectContract.setInspectionMerchandise(null);
        }

        List<ProjectContract> listcjht_fb = projectContractService.getProjectPackageByRole(projectContract);
        return listcjht_fb;
    }

    /**
     * @param filelist
     * @param wjcode
     * @Author:zhaoyongke
     * @Description:获取按钮状态
     * @Date:15:50 2020/12/23
     */
    public void getButFinishStatus(List<SupervisorFile> filelist, String wjcode, Map<String, Object> map) {
        // 判断流程是否进行完
        Boolean isxs = getLcStatus(filelist, wjcode, "");
        // request.setAttribute("finish_status_" + wjcode, isxs);
        map.put("finish_status_" + wjcode, isxs);
    }


    /**
     * @param filelist
     * @param wjcode
     * @Author:zhaoyongke
     * @Description: 判断流程是否结束
     * @Date:14:55 2020/12/31
     */
    public Boolean getLcStatus(List<SupervisorFile> filelist, String wjcode, String type) {
        BaseDict dict = DictUtil.getDictByCode(DictTypes.WJZX, wjcode);
        String lcsl = dict.getBadtLevel3();
        Boolean isxs = true;
        if (StringUtil.isNotBlank(lcsl)) {
            // 流程都结束后才可以显示
            //流程状态0 内部未发起流程1 内部进行中 2 内部流程审核通过3内部流程审核不通过4外部流程进行中5外部流程审核通过（归档）6 外部流程审核不通过
            for (int i = 0; i < filelist.size(); i++) {
                SupervisorFile file = filelist.get(i);
                //流程状态
                String lcstatus = file.getLcStatus();
                // 3 包含外部流和内部流程 2 只包含外部流程   1 只包含内部流程
                if ("3".equals(lcsl) || "2".equals(lcsl)) {
                    if ("001".equals(type)) {

                        if (!"3".equals(lcstatus) && !"5".equals(lcstatus) && !"6".equals(lcstatus) && lcstatus != null && !"".equals(lcstatus)) {
                            // 流程进行 不能删除
                            isxs = false;
                            break;
                        }
                    } else {
                        if (!"5".equals(lcstatus)) {
                            // 流程未结束  不能点击完成按钮 按钮 隐藏
                            isxs = false;
                            break;
                        }
                    }

                } else if ("1".equals(lcsl)) {
                    if ("001".equals(type)) {
                        if (!"2".equals(lcstatus) && !"3".equals(lcstatus) && lcstatus != null && !"".equals(lcstatus)) {
                            // 流程进行 不能删除
                            isxs = false;
                            break;
                        }
                    } else {
                        if (!"2".equals(lcstatus)) {
                            // 流程未结束  不能点击完成按钮 按钮 隐藏
                            isxs = false;
                            break;
                        }
                    }

                }

            }
        }
        return isxs;
    }


    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }

    public void lock(String key, String uuId) {
        int k = 0;
        for (; ; ) {

            System.out.println(redisService);
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            }
            if (k++ >= 1500) {
                throw new RuntimeException("lock error key = " + key);
            }
            int i = new Random().nextInt(30);
            try {
                TimeUnit.MILLISECONDS.sleep(300 + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * @param fbId
     * @Author:zhaoyongke
     * @Description: 检查分包有没有承建单位 没有承建单位不能上传文件
     * @Date:16:18 2021/1/21
     */
    public Boolean checkFbCj(String fbId, String projectId) {
        Boolean isCheck = true;
        ProjectContract contract = projectContractService.selectByPrimaryKey(fbId);
        String code = contract.getCode();
        if (StringUtil.isNotBlank(code)) {
            //查询承建单位
            ProjectUnitConstruction unitConstruction = new ProjectUnitConstruction();
            unitConstruction.setSupervisorProjectId(projectId);
            unitConstruction.setConstructionSubContractNumber(code);
            int count = projectUnitConstructionService.selectCount(unitConstruction);
            if (count == 0) {
                isCheck = false;
            }
        }
        return isCheck;
    }

    /*
     * 下载文件
     * */
    @GetMapping(value = "/exportFile")
    @TokenCheck
    public void exportFile(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");// 文件id
        String url = "";
        Integer downloadCount = 0;
        if (!StringUtil.isBlank(id)) {
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setId(id);
            supervisorFile = supervisorFileService.selectByPrimaryKey(supervisorFile);
            downloadCount = supervisorFile.getDownloads();
            url = supervisorFile.getUrl();
        } else {
            String filename = request.getParameter("filename");// 文件名称
            url = uploadPath + filename;
        }
        //修改下载量:
        SupervisorFile newDownloadFile = new SupervisorFile();
        newDownloadFile.setId(id);
        newDownloadFile.setDownloads(downloadCount == null ? 1 : ++downloadCount);
        supervisorFileService.updateByPrimaryKeySelective(newDownloadFile);
        ExportFileUtil.exportFileApp(response, request, url);
    }

    /**
     * 下载文件权限控制
     */
    @GetMapping(value = "rightControl")
    @ResponseBody
    @TokenCheck
    public JsonUtil rightControl(HttpServletRequest request) {
        JsonUtil re = new JsonUtil();
        String id = request.getParameter("id");// 文件id
        String userId = request.getParameter("userId");//
        if (!StringUtil.isBlank(id)) {
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setId(id);
            supervisorFile = supervisorFileService.selectByPrimaryKey(supervisorFile);
            String role = sysUserService.getUserRoleJlApp(supervisorFile.getProjectId(), userId);
            if ("cj".equals(role)) {
                BaseDict wjdict = DictUtil.getDictByCode(DictTypes.WJ, supervisorFile.getType());
                String level14 = wjdict.getBadtLevel14();
                if (!StringUtil.isBlank(level14)) {
                    if (level14.indexOf(role) < 0) {
                        re.setMsg("您没有权限导出文档");
                        re.setFlag(false);
                        return re;
                    }
                } else {
                    re.setMsg("您没有权限导出文档");
                    re.setFlag(false);
                    return re;
                }
            }
        }
        re.setMsg("成功");
        re.setFlag(true);
        return re;
    }


    /**
     * @param request
     * @param response
     * @Description:
     * @Author:Zhangshuo
     * @Date:2:37 2020-12-19
     */
    @RequestMapping(value = "/img")
    public void loadimg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        if (StringUtil.isNotBlank(id)) {
            SupervisorFile supervisorFile = supervisorFileService.selectByPrimaryKey(id);
            String AsFileName = supervisorFile.getUrl();
            ExportFileUtil.exportFileApp(response, request, AsFileName);
        }
    }


}
